package com.icongyou.enterprise.talent_pool.service.impl;

import com.icongyou.enterprise.talent_pool.entity.vo.AssignmentPerformanceVO;
import com.icongyou.enterprise.talent_pool.entity.vo.AssignmentTagVO;
import com.icongyou.enterprise.talent_pool.mapper.TagMapper;
import com.icongyou.enterprise.talent_pool.service.AIModelService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class CoreCompetenceServiceImplTest {

    @Mock
    private AIModelService aiModelService;

    @Mock
    private TagMapper tagMapper;

    @InjectMocks
    private CoreCompetenceServiceImpl coreCompetenceService;

    private String studentId;
    private String demandText;
    private List<AssignmentTagVO> relevantAssignments;
    private List<AssignmentPerformanceVO> studentPerformances;

    @BeforeEach
    void setUp() {
        studentId = "student-123";
        demandText = "需要Java开发和前端技术";

        // 设置相关任务
        AssignmentTagVO assignment1 = new AssignmentTagVO();
        assignment1.setAssignmentId("assign-1");
        assignment1.setAssignmentName("Java Web开发项目");
        assignment1.setTagId("tag-1");
        assignment1.setRelevance(new BigDecimal("0.95"));
        assignment1.setAssignmentWeight(new BigDecimal("0.85"));

        AssignmentTagVO assignment2 = new AssignmentTagVO();
        assignment2.setAssignmentId("assign-2");
        assignment2.setAssignmentName("前端React开发");
        assignment2.setTagId("tag-2");
        assignment2.setRelevance(new BigDecimal("0.82"));
        assignment2.setAssignmentWeight(new BigDecimal("0.78"));

        relevantAssignments = Arrays.asList(assignment1, assignment2);

        // 设置学生表现
        AssignmentPerformanceVO performance1 = new AssignmentPerformanceVO();
        performance1.setAssignmentId("assign-1");
        performance1.setAssignmentName("Java Web开发项目");
        performance1.setPerformanceScore(new BigDecimal("92.5"));

        AssignmentPerformanceVO performance2 = new AssignmentPerformanceVO();
        performance2.setAssignmentId("assign-2");
        performance2.setAssignmentName("前端React开发");
        performance2.setPerformanceScore(new BigDecimal("88.0"));

        studentPerformances = Arrays.asList(performance1, performance2);
    }

    @Test
    void generateCoreCompetenceLabel_WithValidData_ShouldReturnLabel() {
        // Arrange
        Map<String, Object> mockRequest = new HashMap<>();
        Map<String, Object> mockResponse = new HashMap<>();
        Map<String, Object> mockOutput = new HashMap<>();

        mockOutput.put("text", "Java开发能力突出，熟悉前端技术");
        mockResponse.put("output", mockOutput);

        when(aiModelService.buildAIModelRequest(anyString())).thenReturn(mockRequest);
        when(aiModelService.callAIModelAPI(mockRequest)).thenReturn(mockResponse);
        when(tagMapper.getTagNameById(anyString())).thenReturn("Java开发");

        // Act
        String result = coreCompetenceService.generateCoreCompetenceLabel(
                demandText, studentId, relevantAssignments, studentPerformances);

        // Assert
        assertNotNull(result);
        assertEquals("Java开发能力突出，熟悉前端技术", result);
        verify(aiModelService).buildAIModelRequest(anyString());
        verify(aiModelService).callAIModelAPI(mockRequest);
    }

    @Test
    void generateCoreCompetenceLabel_WithAIModelException_ShouldReturnFallbackLabel() {
        // Arrange
        when(aiModelService.buildAIModelRequest(anyString())).thenReturn(new HashMap<>());
        when(aiModelService.callAIModelAPI(any())).thenThrow(new RuntimeException("AI服务异常"));

        // Act
        String result = coreCompetenceService.generateCoreCompetenceLabel(
                demandText, studentId, relevantAssignments, studentPerformances);

        // Assert
        assertNotNull(result);
        assertFalse(result.isEmpty());
        // 验证返回的是降级标签之一
        assertTrue(result.matches("技术基础扎实，学习能力强|具备良好的编程能力和问题解决能力|专业知识掌握牢固，实践能力良好|综合能力均衡，发展潜力大|技术理解深入，应用能力突出"));
    }

    @Test
    void generateCoreCompetenceLabel_WithEmptyAssignments_ShouldStillWork() {
        // Arrange
        Map<String, Object> mockRequest = new HashMap<>();
        Map<String, Object> mockResponse = new HashMap<>();
        Map<String, Object> mockOutput = new HashMap<>();

        mockOutput.put("text", "具备良好的学习能力");
        mockResponse.put("output", mockOutput);

        when(aiModelService.buildAIModelRequest(anyString())).thenReturn(mockRequest);
        when(aiModelService.callAIModelAPI(mockRequest)).thenReturn(mockResponse);

        // Act
        String result = coreCompetenceService.generateCoreCompetenceLabel(
                demandText, studentId, Collections.emptyList(), studentPerformances);

        // Assert
        assertNotNull(result);
        assertEquals("具备良好的学习能力", result);
    }

    @Test
    void generateCoreCompetenceLabel_WithNullDemandText_ShouldStillWork() {
        // Arrange
        Map<String, Object> mockRequest = new HashMap<>();
        Map<String, Object> mockResponse = new HashMap<>();
        Map<String, Object> mockOutput = new HashMap<>();

        mockOutput.put("text", "Java开发能力突出");
        mockResponse.put("output", mockOutput);

        when(aiModelService.buildAIModelRequest(anyString())).thenReturn(mockRequest);
        when(aiModelService.callAIModelAPI(mockRequest)).thenReturn(mockResponse);
        when(tagMapper.getTagNameById(anyString())).thenReturn("Java开发");

        // Act
        String result = coreCompetenceService.generateCoreCompetenceLabel(
                null, studentId, relevantAssignments, studentPerformances);

        // Assert
        assertNotNull(result);
        assertEquals("Java开发能力突出", result);
    }

    @Test
    void generateCoreCompetenceLabel_WithNullPerformance_ShouldHandleGracefully() {
        // Arrange
        Map<String, Object> mockRequest = new HashMap<>();
        Map<String, Object> mockResponse = new HashMap<>();
        Map<String, Object> mockOutput = new HashMap<>();

        mockOutput.put("text", "具备相关技术能力");
        mockResponse.put("output", mockOutput);

        when(aiModelService.buildAIModelRequest(anyString())).thenReturn(mockRequest);
        when(aiModelService.callAIModelAPI(mockRequest)).thenReturn(mockResponse);
        when(tagMapper.getTagNameById(anyString())).thenReturn("Java开发");

        // Act - 传入空的performance列表而不是null
        String result = coreCompetenceService.generateCoreCompetenceLabel(
                demandText, studentId, relevantAssignments, Collections.emptyList());

        // Assert
        assertNotNull(result);
        assertEquals("具备相关技术能力", result);
    }

    @Test
    void parseCoreCompetenceResponse_WithValidResponse_ShouldParseCorrectly() {
        // Arrange
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> output = new HashMap<>();
        output.put("text", "\"Java开发专家\"");
        response.put("output", output);

        // Act
        String result = coreCompetenceService.parseCoreCompetenceResponse(response);

        // Assert
        assertEquals("Java开发专家", result);
    }

    @Test
    void parseCoreCompetenceResponse_WithEmptyText_ShouldReturnFallback() {
        // Arrange
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> output = new HashMap<>();
        output.put("text", "");
        response.put("output", output);

        // Act
        String result = coreCompetenceService.parseCoreCompetenceResponse(response);

        // Assert
        assertNotNull(result);
        // 应该是降级标签
        assertFalse(result.isEmpty());
    }

    @Test
    void parseCoreCompetenceResponse_WithNullOutput_ShouldReturnFallback() {
        // Arrange
        Map<String, Object> response = new HashMap<>();
        response.put("output", null);

        // Act
        String result = coreCompetenceService.parseCoreCompetenceResponse(response);

        // Assert
        assertNotNull(result);
        // 应该是降级标签
        assertFalse(result.isEmpty());
    }

    @Test
    void getFallbackCoreCompetenceLabel_ShouldReturnValidLabel() {
        // Act
        String result = coreCompetenceService.getFallbackCoreCompetenceLabel();

        // Assert
        assertNotNull(result);
        assertFalse(result.isEmpty());
        // 验证返回的是预定义的降级标签之一
        assertTrue(result.matches("技术基础扎实，学习能力强|具备良好的编程能力和问题解决能力|专业知识掌握牢固，实践能力良好|综合能力均衡，发展潜力大|技术理解深入，应用能力突出"));
    }
}